import {
  asyncRoutes,
  constantRoutes,
  fastenRoutes,
  rootInfoRoute,
  rootUserRoute,
  taskWallRoute,
  freeboxRoute,
  dashboardRoute
} from '@/router'

import {
  completePermission,
  permissionByUser
} from '@/api/permission/permission.js'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true // false?
  }
}

/**
 * Filter asynchronous routing tables by recursion(递归)
 * @param routes asyncRoutes
 * @param roles
 */

export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = {
      ...route
    }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

/* 路由权限开始*/

// 1获取全部权限及用户拥有权限
function lookupPower() {
  return new Promise((resolve, reject) => {
    let allPower = []
    let userPower = []
    completePermission().then(res => {
      // 获取完整权限树
      allPower = res.data
      permissionByUser().then(res => {
        // 获取用户所拥有的权限
        userPower = res.data
        const routesData = relevanceHandle(allPower, userPower)
        resolve(routesData)
      })
    })
  })
}

// 2全部权限树拆解
function relevanceHandle(all, user) {
  let list = [] // 权限合集
  for (let i = 0; i < all.length; i++) {
    list = list.concat(all[i].permissionList)
  }
  return standardizedHandle(list, user)
}

// 3查找对应权限
function standardizedHandle(all, user) {
  const list = [] // id所对应权限
  for (let i = 0; i < user.length; i++) {
    const itemData = all.find(item => item.id === user[i])
    if (itemData) {
      list.push(itemData)
    }
  }
  const parentData = duplicateRemoval(list) // 权限所对应父级

  const parentIdData = [] // 父级id
  for (let k = 0; k < parentData.length; k++) {
    parentIdData.push(parentData[k].parentId)
  }
  // parentIdData
  return handleAsyncRoutes(asyncRoutes, parentIdData, user)

  // parentIdData //对应路由id
}

// 父级去重
function duplicateRemoval(arr) {
  const res = new Map()
  return arr.filter((item) => !res.has(item.parentId) && res.set(item.parentId, 1))
}

// 根据父级权限id查找对应子级路由
function handleAsyncRoutes(data, ids, user) {
  const superList = []

  function inspection(data) {
    if (data.length == 0) { return data }
    data.forEach(element => {
      if (element.meta) {
        if (element.meta.id) {
          if (ids.indexOf(element.meta.id) != -1) {
            superList.push(element)
          }
        } else { // 没id
          if (element.children) {
            return inspection(element.children)
          }
        }
      }
    })
  }

  inspection(data)
  return regularRouters(superList, ids, user)
}

// 动态路由item插入固定路由表对应位置
function regularRouters(routeItems, ids, user) {
  for (let i = 0; i < routeItems.length; i++) {
    const route = routeItems[i]
    if (route.meta.tallest) {
      fastenRoutes.push(route)
    } else {
      insert(fastenRoutes, route)
    }
  }

  function insert(data, route) {
    data.forEach(element => {
      if (element.name) {
        if (element.name == route.meta.parentName) {
          element.children.push(route)
          return
        } else {
          if (element.children) {
            return insert(element.children, route)
          }
        }
      }
    })
  }
  return deleteWuxia(fastenRoutes, ids, user)
}

// 隐藏下级不存在的路由
function deleteWuxia(routelist, ids, user) {
  const routeCollection = routelist.concat()

  function hideHandle(data) {
    data.forEach(element => {
      if (!element.meta.id) {
        if (element.children) {
          if (element.children.length === 0) {
            element.hidden = true
          } else {
            const list = []
            for (let i = 0; i < element.children.length; i++) {
              const itemData = element.children[i]
              if (itemData.meta.id || (itemData.children && itemData.children.length > 0)) {
                list.push(itemData)
              }
            }
            if (list.length == 0) {
              element.hidden = true
            } else {
              return hideHandle(element.children)
            }
          }
        }
      }
    })
  }

  hideHandle(routeCollection)

  // 单独处理信息管理
  const rootInfoItem = rootInfoHandle(ids, user)
  if (JSON.stringify(rootInfoItem) != '{}') {
    routeCollection.push(rootInfoItem)
  }

  // 单独处理用户管理
  const rootUserItem = rootUserHandle(ids, user)
  if (JSON.stringify(rootUserItem) != '{}') {
    routeCollection.push(rootUserItem)
  }

  const taskWallItem = taskWallHandle(ids, user)
  if (JSON.stringify(taskWallItem) != '{}') {
    routeCollection.push(taskWallItem)
  }

  const freeboxItem = freeBoxHandle(ids, user)
  if (JSON.stringify(freeboxItem) != '{}') {
    const itemData = routeCollection.find(item => item.name == 'Rootplayrules')
    itemData.children.unshift(freeboxItem)
  }

  const Rootdatamanager = routeCollection.find(item => item.name == 'Rootdatamanager')
  if (Rootdatamanager) {
    if (Rootdatamanager.children[0].hidden) {
      Rootdatamanager.hidden = true
    } else {
      Rootdatamanager.children[0].children = sortHandle(Rootdatamanager.children[0].children, 'alone')
    }
  }

  return sortHandle(routeCollection, 'all')
}

// 单独处理信息管理
function rootInfoHandle(ids, user) {
  if (ids.indexOf(2) != -1) {
    if (user.indexOf(5) == -1 && user.indexOf(177) == -1 && user.indexOf(178) == -1) {
      rootInfoRoute.children[0].hidden = true
    }

    if (user.indexOf(6) == -1) {
      rootInfoRoute.children[1].hidden = true
    }

    return rootInfoRoute
  } else {
    return {}
  }
}

// 单独处理用户管理
function rootUserHandle(ids, user) {
  if (ids.indexOf(3) != -1 || ids.indexOf(4) != -1 || ids.indexOf(5) != -1 || ids.indexOf(6) != -1 || ids.indexOf(53) != -1 || ids.indexOf(55) != -1 || ids.indexOf(68) != -1 || ids.indexOf(260) != -1 || ids.indexOf(261) != -1) {
    if (ids.indexOf(68) != -1 || ids.indexOf(260) != -1 || ids.indexOf(261) != -1) {
      rootUserRoute.children.push({
        path: 'user-behavier',
        name: 'Userbehavier',
        component: () => import('@/views/uswebehavier/index'),
        meta: {
          id: 68,
          title: '行为管理'
        }
      })
    }
    return rootUserRoute
  }
  return {}
}

// 单独处理任务墙
function taskWallHandle(ids, user) {
  if (ids.indexOf(17) != -1 || ids.indexOf(18) != -1 || ids.indexOf(19) != -1) {
    if (ids.indexOf(17) == -1) {
      taskWallRoute.children[0].hidden = true
    }
    if (ids.indexOf(18) == -1 && ids.indexOf(19) == -1) {
      taskWallRoute.children[1].hidden = true
    }
    return taskWallRoute
  } else {
    return {}
  }
}

// 单独处理免费箱子
function freeBoxHandle(ids, user) {
  if (ids.indexOf(8) != -1 || ids.indexOf(9) != -1 || ids.indexOf(10) != -1) {
    return freeboxRoute
  } else {
    return {}
  }
}

// 路由排序
function sortHandle(routeCollection, key) {
  function compare(property) {
    return function(a, b) {
      const value1 = a[property]
      const value2 = b[property]
      return value1 - value2
    }
  }
  const routeList = routeCollection.sort(compare('sort'))
  // 别他妈动
  routeList.forEach(item => {
    if (item.path == '/rootplayrules') {
      item.children.sort(compare('sortNum'))
    }
  })

  if (key == 'all') {
    const nothing = {
      path: '*',
      name: '404',
      redirect: '/404',
      hidden: true
    }

    routeList.push(nothing)
    if (routeList[0].meta.id !== 1) {
      routeList.unshift(dashboardRoute)
    }
  }

  return routeList
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    console.log(routes)
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({
    commit
  }, roles) {
    return new Promise(resolve => {
      // let accessedRoutes = []
      lookupPower().then(res => {
        commit('SET_ROUTES', res)
        resolve(res)
      })
      // 全部
      // commit('SET_ROUTES', allRoutes)
      // resolve(allRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
